package com.elitel.frame.base.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.elitel.frame.base.service.GroupService;
import com.elitel.frame.core.util.FileControlUtil;
import com.elitel.frame.core.util.FreemarkerUtil;
import com.elitel.frame.main.entity.CfgGroup;
import com.elitel.frame.main.entity.vo.ZTreeDataModelVo;

@Controller
@RequestMapping("/system/pageConfig")
public class PageConfigurationController {
	private static final Logger logger = LoggerFactory.getLogger(PageConfigurationController.class);

	@Autowired
	private GroupService groupService;

	/**
	 * <pre>
	 * pageGenerator(界面系统首页面一键生成)   
	 * &#64;author：FanWenquan    
	 * &#64;date：2017年11月2日 上午11:28:16   
	 * &#64;param systemId
	 * &#64;param request
	 * &#64;param response
	 * &#64;return
	 * </pre>
	 */
	@RequestMapping(value = "/generator", produces = "application/json; charset=utf-8")
	@ResponseBody
	public String pageGenerator(String systemId, HttpServletRequest request, HttpServletResponse response) {
		CfgGroup group = groupService.getGroupBySystemId(systemId);
		String sysTitle = "";
		String sysModJson = "";
		//String sysFileName = "";
		//String vueTemplate = "";
		String fileName = "";
		String projectName = "";
		List<String> indexList = null;
		ZTreeDataModelVo sysmodJson = new ZTreeDataModelVo();
		try {
			if (null != group) {
				projectName = group.getGroupid().toString();
				sysTitle = group.getGroupname();
				fileName = group.getGroupid().toString();
				sysmodJson.setId(group.getGroupid().toString());
				sysmodJson.setFatureid(group.getFatureid().toString());
				sysmodJson.setName(group.getGroupname());
				sysmodJson.setIsMark(group.getServerGuid());
				sysmodJson.setHint(group.getServerUrl());
				sysmodJson.setIconClose("css/zTree/zTreeStyle/img/diy/1_open.png");
				sysmodJson.setIconOpen("css/zTree/zTreeStyle/img/diy/1_close.png");
				sysmodJson.setIcon("css/zTree/zTreeStyle/img/diy/8.png");
				List<ZTreeDataModelVo> groupListForTree = groupService.getGroupListForTree(group.getGroupid());
				sysmodJson.setChildren(groupListForTree);
				indexList = getVueRouter(groupListForTree, group.getGroupid().toString());
				sysModJson = JSON.toJSONString(groupListForTree);
			}
			String newPath = request.getSession().getServletContext()
					.getRealPath("/workspace/src/" + group.getGroupid());
			String oldPath = request.getSession().getServletContext().getRealPath("/workspace/src/template");
			// 复制文件
			FileControlUtil.copyFolder(oldPath, newPath);
			// 删除复制之后的ftl的文件
			String indexDel = request.getSession().getServletContext()
					.getRealPath("/workspace/src/" + group.getGroupid() + "/router/index.ftl");
			String herderDel = request.getSession().getServletContext()
					.getRealPath("/workspace/src/" + group.getGroupid() + "/page/common/ProHeader.ftl");
			String siderDel = request.getSession().getServletContext()
					.getRealPath("/workspace/src/" + group.getGroupid() + "/page/common/ProSidebar.ftl");
			FileControlUtil.deleteFile(indexDel);
			FileControlUtil.deleteFile(herderDel);
			FileControlUtil.deleteFile(siderDel);
			// ftl模板路径
			String indexPath = request.getSession().getServletContext().getRealPath("/workspace/src/template/router");
			String herderPath = request.getSession().getServletContext()
					.getRealPath("/workspace/src/template/page/common");
			String siderPath = request.getSession().getServletContext()
					.getRealPath("/workspace/src/template/page/common");
			// 输出vue的路径
			String indexOutVue = request.getSession().getServletContext()
					.getRealPath("/workspace/src/" + group.getGroupid() + "/router/index.js");
			String herderVue = request.getSession().getServletContext()
					.getRealPath("/workspace/src/" + group.getGroupid() + "/page/common/ProHeader.vue");
			String siderVue = request.getSession().getServletContext()
					.getRealPath("/workspace/src/" + group.getGroupid() + "/page/common/ProSidebar.vue");
			Map<String, Object> indexMap = new HashMap<String, Object>();
			indexMap.put("routers", indexList);
			FreemarkerUtil.freeMarkerprint("index.ftl", indexPath, indexMap, indexOutVue);
			Map<String, Object> herderMap = new HashMap<String, Object>();
			herderMap.put("sysTitle", sysTitle);
			FreemarkerUtil.freeMarkerprint("ProHeader.ftl", herderPath, herderMap, herderVue);
			Map<String, Object> siderMap = new HashMap<String, Object>();
			siderMap.put("sysModJson", sysModJson);
			FreemarkerUtil.freeMarkerprint("ProSidebar.ftl", siderPath, siderMap, siderVue);
			String workFile = request.getSession().getServletContext().getRealPath("/workspace");
			//paint.vue 复制
			String sourPath = request.getSession().getServletContext().getRealPath("/workspace/src/template/page/paint/paint.vue");
			for (String stri : indexList) {
				String targetPath = request.getSession().getServletContext()
						.getRealPath("/workspace/src/" + group.getGroupid() + "/page/paint/" + stri + ".vue");
				FileControlUtil.copyFile(sourPath, targetPath);
			}
			//执行打包命令！
			Runtime r = Runtime.getRuntime();
			File dir = new File(workFile);
			String command = "c:\\windows\\system32\\cmd.exe /c npm run build -- "+projectName;
			r.exec(command, null, dir);
			//输出控制台信息到日志文件
			Process p = r.exec(command, null, dir);
			BufferedReader br = new BufferedReader(new
			InputStreamReader(p.getInputStream()));
			StringBuffer sb = new StringBuffer();
			String inline;
			SimpleDateFormat formatSec = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String dateSec = formatSec.format(new Date());
			sb.append("系统："+fileName +"--当前时间："+ dateSec).append("\r\n");
			while (null != (inline = br.readLine())) {
			sb.append(inline).append("\r\n");
			}
			br.close();
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
	        String dateString = formatter.format(new Date());
			String logPath = request.getSession().getServletContext().getRealPath("/workspace/logs/system_"+fileName +"_"+ dateString+".log");
			FileControlUtil.appendMethodB(logPath, sb.toString());
			System.out.println(sb.toString());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(),e);
		}
		return "界面生成成功";
	}

	public List<String> getVueRouter(List<ZTreeDataModelVo> list, String groupId) {
		List<String> slist = new ArrayList<String>();
		for (ZTreeDataModelVo ztr : list) {
			if (null != ztr) {
				slist.add(ztr.getIsMark()+"_"+groupId);
				if (ztr.getChildren().size() > 0 && ztr.getChildren() != null) {
					List<String> vueRouter = getVueRouter(ztr.getChildren(), groupId);
					for (String string : vueRouter) {
						slist.add(string);
					}
				}
			}
		}
		return slist;
	}
}
